// 将此文件内容复制到App.js，运行npm start即可查看效果。
import React, { useCallback, useEffect, useRef } from 'react';
import {
  ReactFlow,
  Handle,
  useNodesState,
  useEdgesState,
  addEdge,
} from 'reactflow';
import 'reactflow/dist/style.css';

// 自定义节点组件
const InfoNode = ({ data }) => {
  const nodeRef = useRef(null);

  useEffect(() => {
    const nodeEl = nodeRef.current;
    if (!nodeEl) return;

    const handleClick = () => alert('This is the info of the node');
    const handleMouseEnter = () => console.log('Mouse entered the node');
    const handleMouseLeave = () => console.log('Mouse left the node');

    nodeEl.addEventListener('click', handleClick);
    nodeEl.addEventListener('mouseenter', handleMouseEnter);
    nodeEl.addEventListener('mouseleave', handleMouseLeave);

    // 清理
    return () => {
      nodeEl.removeEventListener('click', handleClick);
      nodeEl.removeEventListener('mouseenter', handleMouseEnter);
      nodeEl.removeEventListener('mouseleave', handleMouseLeave);
    };
  }, []); // 空依赖数组，确保只在挂载和卸载时执行

  return (
    <div
      ref={nodeRef}
      className="react-flow__node-default"
    >
      {data.label}
    </div>
  );
};

const nodeTypes = {
  infoNode: InfoNode,
};

// 节点配置
const infoNode = {
  id: 'info-node-1',      // 修正后的 ID（去掉空格）
  type: 'infoNode',       // 指定自定义类型
  data: { label: 'Info Node' },
  position: { x: 250, y: 100 },  // 调整到可见位置
};

const initialNodes = [infoNode];
const initialEdges = [];

export default function App() {
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);

  const onConnect = useCallback(
    (params) => setEdges((eds) => addEdge(params, eds)),
    [setEdges]
  );

  return (
    <div style={{ width: '100vw', height: '100vh' }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        nodeTypes={nodeTypes}  // 注册自定义类型
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        fitView
      />
    </div>
  );
}
